//
//  THBabyComitOrderViewController.m
//  TreeHole
//
//  Created by apple on 2020/9/23.
//  Copyright © 2020 stoneobs. All rights reserved.
//

#import "THBabyComitOrderViewController.h"

@interface THBabyComitOrderViewController ()
@property(nonatomic, strong) NSMutableArray<NSArray*>                     *dataSouce;/**<  */
@property(nonatomic, strong) YYLabel                      *chatLable;/**< u */
@property(nonatomic, strong) STButton                     *agreeButton;/**<  */

@property(nonatomic, strong) NSString                     *service_at;/**<  */
@end

@implementation THBabyComitOrderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"确认订单";
    [self stoneobs_ui_configSubView];
    [self config_dataSouce];
    [self configBootomView];
    [self stoneobs_fun_st_autoAdjustAllResponder];
    // Do any additional setup after loading the view.
}
- (void)configBootomView{
    UIView * bootomView = [[UIView alloc] initWithFrame:CGRectMake(0, TMUtils.stoneobs_fun_get_tabBarTop, STONEOBS_UI_UISCREEN_WIDTH, 49 + 50)];
    [self.view addSubview:bootomView];
    bootomView.backgroundColor = UIColor.whiteColor;
    [bootomView stoneobs_fun_st_showTopShadow];
    
    STLabel * stoneobs_ui_label = [[STLabel alloc] initWithFrame:CGRectMake(16, 0, 200, 49)
                                                            text:[NSString stringWithFormat:@"合计:￥%0.2f",self.model.price.floatValue]
                                                       textColor:WH_UICOLOR_FROM_RGBA(0xFF2F3D)
                                                            font:15
                                                     isSizetoFit:NO
                                                   textAlignment:NSTextAlignmentLeft];
    [bootomView addSubview:stoneobs_ui_label];
    stoneobs_ui_label.attributedText = [stoneobs_ui_label.text stoneobs_fun_st_convertAttributeStringWithKeyWord:@"合计:" attributes:@{
        NSForegroundColorAttributeName:STONEOBS_UI_SECEND_TEXT_COLOR
    }];
    __weak typeof(self) weakSelf =  self;
    STButton * stoneobs_ui_button = [[STButton alloc] initWithFrame:CGRectMake(10, 0, 90, 30)
                                                              title:@"提交订单"
                                                         titleColor:UIColor.whiteColor
                                                          titleFont:13
                                                       cornerRadius:15
                                                    backgroundColor:STONEOBS_UI_THEME_BACKGROUNDCOLOR
                                                    backgroundImage:nil
                                                              image:nil];
    stoneobs_ui_button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    stoneobs_ui_button.centerY = 24.5;
    [bootomView addSubview:stoneobs_ui_button];
    stoneobs_ui_button.backgroundColor = [UIColor colorWithGradientStyle:UIGradientStyleTopToBottom withFrame:stoneobs_ui_button.bounds andColors:@[WH_UICOLOR_FROM_RGBA(0x56BD49),WH_UICOLOR_FROM_RGBA(0x25B13A)]];
    stoneobs_ui_button.right = STONEOBS_UI_UISCREEN_WIDTH - 10;
    [stoneobs_ui_button setClicAction:^(UIButton *sender) {
        [weakSelf onSelctedCommitButton];

    }];
    
    CGFloat top = bootomView.top - 50;
    STButton * cbutton = [[STButton alloc] initWithFrame:CGRectMake(15, top, 40, 40)
                                                   title:@""
                                              titleColor:UIColor.whiteColor
                                               titleFont:15
                                            cornerRadius:0
                                         backgroundColor:nil
                                         backgroundImage:nil
                                                   image:[UIImage imageNamed:@"wxzzf"]];
        cbutton.selected = YES;
    [cbutton setImage:[UIImage imageNamed:@"gx"] forState:UIControlStateSelected];
    [cbutton stoneobs_fun_touch_handle:^(UIButton *sender) {
        sender.selected = !sender.selected ;
    }];
    [self.view addSubview:cbutton];
    self.agreeButton = cbutton;
    
    self.chatLable = [YYLabel new];
    self.chatLable.numberOfLines = 0;
    [self.view addSubview:self.chatLable];
    self.chatLable.layer.cornerRadius = 4;
    self.chatLable.clipsToBounds = YES;
    self.chatLable.displaysAsynchronously=YES;
    self.chatLable.userInteractionEnabled = YES;
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSMutableAttributedString  *resultAttr = [[NSMutableAttributedString alloc] initWithString:@""];
        resultAttr.alignment = NSTextAlignmentLeft;
        resultAttr.lineSpacing = 3;
        ({
            NSMutableAttributedString *headerText = [[NSMutableAttributedString alloc] initWithString:@"购买则代表同意"];
            [headerText setColor:STONEOBS_UI_FIRST_TEXT_COLOR range:headerText.rangeOfAll];
            headerText.font = [UIFont systemFontOfSize:15];
            [resultAttr appendAttributedString:headerText];
        });
        ({
            NSString * title = @"《服务合同》";
            NSMutableAttributedString *headerText = [[NSMutableAttributedString alloc] initWithString:title];
            [headerText setColor:FlatBlue range:headerText.rangeOfAll];
            headerText.font = [UIFont systemFontOfSize:15];
            [resultAttr appendAttributedString:headerText];
            
            ({
                YYTextHighlight *highlight = [YYTextHighlight new];
                [highlight setColor:[UIColor whiteColor]];
                highlight.tapAction = ^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect) {
                    
                    [BFBaseConfigDataController stoneobs_fun_get_keyword:@"service_contract" handle:^(NSString * _Nonnull h5String) {
                        STTools_WebViewController * webVc = [[STTools_WebViewController alloc] initWithH5String:h5String];
                        webVc.forceTitle = @"服务合同";
                        [self pushViewController:webVc animated:1];
                    }];
                    
                };
                NSString * nameTitle = resultAttr.string;
                NSRange range = [nameTitle rangeOfString:title];
                [resultAttr setTextHighlight:highlight range:range];
            });
        });
        
        YYTextContainer *titleContarer = [YYTextContainer new];
        titleContarer.size = CGSizeMake(CGFLOAT_MAX,40);
        
        YYTextLayout *titleLayout = [YYTextLayout layoutWithContainer:titleContarer text:resultAttr];
        CGFloat titleLabelWith= titleLayout.textBoundingSize.width;
        
        dispatch_async(dispatch_get_main_queue(), ^{
            self.chatLable.textLayout = titleLayout;
            self.chatLable.frame = CGRectMake(self.agreeButton.right,0, titleLabelWith+10, 24);
            self.chatLable.centerY = self.agreeButton.centerY;
            
            
        });
    });
}
#pragma mark --configSubView
- (void)stoneobs_ui_configSubView{
    UIView * header = [[UIView alloc] initWithFrame:STONEOBS_UI_UISCREEN_FRAME];
    header.backgroundColor = UIColor.whiteColor;
    CGFloat top = 10;
    ({
        STLabel * stoneobs_ui_label = [[STLabel alloc] initWithFrame:CGRectMake(15, top, 200, 20)
                                                                text:@"服务信息"
                                                           textColor:STONEOBS_UI_FIRST_TEXT_COLOR
                                                                font:12
                                                         isSizetoFit:NO
                                                       textAlignment:NSTextAlignmentLeft];
        [header addSubview:stoneobs_ui_label];
        stoneobs_ui_label.font = [UIFont fontWithName:STONEOBS_UI_FONT_CU_NAME size:12];
        top = stoneobs_ui_label.bottom+10;
    });
    
    ({
        STLabel * stoneobs_ui_label = [[STLabel alloc] initWithFrame:CGRectMake(15, top, 200, 20)
                                                                text:[NSString stringWithFormat:@"服务类目:%@",self.model.major_name]
                                                           textColor:STONEOBS_UI_FIRST_TEXT_COLOR
                                                                font:12
                                                         isSizetoFit:NO
                                                       textAlignment:NSTextAlignmentLeft];
        [header addSubview:stoneobs_ui_label];
        top = stoneobs_ui_label.bottom+10;
    });
    
    ({
        STLabel * stoneobs_ui_label = [[STLabel alloc] initWithFrame:CGRectMake(15, top, 200, 20)
                                                                text:[NSString stringWithFormat:@"服务师傅:%@",self.model.real_name]
                                                           textColor:STONEOBS_UI_FIRST_TEXT_COLOR
                                                                font:12
                                                         isSizetoFit:NO
                                                       textAlignment:NSTextAlignmentLeft];
        [header addSubview:stoneobs_ui_label];
        top = stoneobs_ui_label.bottom+10;
    });
    
    ({
        UIView * stoneobs_ui_line = [[UIView alloc] initWithFrame:CGRectMake(0, top, UISCREEN_WIDTH, 10)];
        stoneobs_ui_line.backgroundColor = self.tableView.backgroundColor;
        [header addSubview:stoneobs_ui_line];
        top = stoneobs_ui_line.bottom;
    });
    
    ({
        STLabel * stoneobs_ui_label = [[STLabel alloc] initWithFrame:CGRectMake(15, top+8, 200, 20)
                                                                text:@"订单信息"
                                                           textColor:STONEOBS_UI_FIRST_TEXT_COLOR
                                                                font:12
                                                         isSizetoFit:NO
                                                       textAlignment:NSTextAlignmentLeft];
        [header addSubview:stoneobs_ui_label];
        stoneobs_ui_label.font = [UIFont fontWithName:STONEOBS_UI_FONT_CU_NAME size:12];
        top = stoneobs_ui_label.bottom;
    });
    
    header.height = top;
    self.tableView.tableHeaderView = header;
}
- (void)config_dataSouce{
    self.dataSouce = NSMutableArray.new;
    ({
        NSArray * array = @[
            [[STTools_TableEasyModel alloc] initWithTextString:@"姓名" accessoryView:[self textFiledFromPlaceHolder:@"请填写姓名"]],
            [[STTools_TableEasyModel alloc] initWithTextString:@"联系方式" accessoryView:[self textFiledFromPlaceHolder:@"请填写联系方式"]],
            [[STTools_TableEasyModel alloc] initWithTextString:@"服务地址" accessoryView:[self textFiledFromPlaceHolder:@"请填写服务地址"]],
            [[STTools_TableEasyModel alloc] initWithTextString:@"服务时间" detailString:@"请选择服务时间"],
            
        ];
        [self.dataSouce addObject:array];
    });
    
    [self.tableView reloadData];
}
- (UITextField*)textFiledFromPlaceHolder:(NSString*)placeholder{
    UITextField * textFiled = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, UISCREEN_WIDTH*0.6, 50)];
    textFiled.textAlignment = NSTextAlignmentRight;
    textFiled.placeholder = placeholder;
    textFiled.font = [UIFont systemFontOfSize:13];
    textFiled.textColor = WH_UICOLOR_FROM_RGBA(0x999999);
    return textFiled;
}
#pragma --mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return self.dataSouce.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataSouce[section].count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 50;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 20;
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * reuseIdentifier =  @"cell";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuseIdentifier];
        
    }
    STTools_TableEasyModel * model = self.dataSouce[indexPath.section][indexPath.row];
    [cell setSt_tableEasyModel:model];
    
    return cell;
}
#pragma --mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    STTools_TableEasyModel * model = self.dataSouce[indexPath.section][indexPath.row];
    if ([model.textString isEqualToString:@"服务时间"]) {
        STTools_PickerViewController * datePicker = [[STTools_PickerViewController alloc] initWithDefualtDatePickerWithHandle:^(NSDate *date) {
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                NSMutableArray * hourarry = NSMutableArray.new;
                for (NSInteger i = 0; i < 24; i ++) {
                    if (i < 10) {
                        [hourarry addObject:[NSString stringWithFormat:@"0%@",@(i)]];
                    }else{
                        [hourarry addObject:@(i).description];
                    }
                    
                }
                NSMutableArray * speArray = @[@":"].mutableCopy;
                NSMutableArray * minarry = NSMutableArray.new;
                for (NSInteger i = 0; i < 60; i ++) {
                    if (i < 10) {
                        [minarry addObject:[NSString stringWithFormat:@"0%@",@(i)]];
                    }else{
                        [minarry addObject:@(i).description];
                    }
                    
                }
                STTools_PickerViewController * timePicker = [[STTools_PickerViewController alloc] initWithPickerArray:@[hourarry,speArray,minarry] andWithHandle:^(NSArray<NSString *> *stringArray) {
                    
                    model.detailString = [NSString stringWithFormat:@"%@ %@",date.stoneobs_fun_yyyyMMddByLineWithDate,[stringArray componentsJoinedByString:@""]];
                    self.service_at = model.detailString;
                    [self.tableView reloadData];
                }];
                [self presentViewController:timePicker animated:NO completion:nil];
                
            });
            
        }];
        [self presentViewController:datePicker animated:NO completion:nil];
    }
    
    [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
}
- (STTools_TableEasyModel*)modelFormText:(NSString*)text{
    for (STTools_TableEasyModel * model in self.dataSouce.stoneobs_fun_dissolveArray) {
        if ([model.textString containsString:text]) {
            return model;
        }
    }
    return nil;
}
#pragma mark --stoneobs Action Method
- (void)onSelctedCommitButton{
    if (!self.service_at.length) {
        [SVProgressHUD showInfoWithStatus:@"请选择服务时间"];
        return;
    }
    if (!self.agreeButton.selected) {
        [SVProgressHUD showInfoWithStatus:@"请同意协议"];
        return;
    }
    
    
    NSMutableDictionary * stoneobs_net_param_dic = [NSMutableDictionary new];
    NSString * stoneobs_net_user_id = [STTools_UserManger defult].stoneobs_fun_get_loginedUser.uid.description;
    NSString * stoneobs_net_user_token = STTools_UserManger.defult.stoneobs_fun_get_loginedUser.token;
    if (stoneobs_net_user_id.length) {
        [stoneobs_net_param_dic setObject:stoneobs_net_user_id forKey:@"uid"];
    }
    if (stoneobs_net_user_token.length) {
        [stoneobs_net_param_dic setObject:stoneobs_net_user_token forKey:@"token"];
    }
    ({
        STTools_TableEasyModel * model = [self modelFormText:@"姓名"];
        UITextField * textFiled = (id)model.accessoryView;
        [stoneobs_net_param_dic setObject:textFiled.text forKey:@"name"];
    });
    ({
        STTools_TableEasyModel * model = [self modelFormText:@"联系方式"];
        UITextField * textFiled = (id)model.accessoryView;
        [stoneobs_net_param_dic setObject:textFiled.text forKey:@"phone"];
    });
    ({
        STTools_TableEasyModel * model = [self modelFormText:@"服务地址"];
        UITextField * textFiled = (id)model.accessoryView;
        [stoneobs_net_param_dic setObject:textFiled.text forKey:@"address"];
    });
    [stoneobs_net_param_dic setObject:self.model.user_id forKey:@"major_user_id"];
    [stoneobs_net_param_dic setObject:self.userModel.major_id forKey:@"major_id"];
    [stoneobs_net_param_dic setObject:self.service_at forKey:@"service_at"];
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSString * stoneobs_net_net_url = [NSString stringWithFormat:@"%@%@",RELEASE_SERVER_URL_HEADER,@"v1/nursery/order"];
    DDLogInfo(@"url:%@",stoneobs_net_net_url);
    DDLogInfo(@"param:%@",stoneobs_net_param_dic);
    [[STTools_NetWrokManger defaultClient] stoneobs_fun_requestWithPath:stoneobs_net_net_url
                                                                 method:STHttpRequestType_stoneobs_enumPost
                                                             parameters:stoneobs_net_param_dic
                                                                success:^(NSURLSessionDataTask *operation, id responseObject) {
        [SVProgressHUD dismiss];
        NSString * data = [[responseObject valueForKey:@"data"] description];
        THZhiFuViewController * vc = THZhiFuViewController.new;
        vc.pay_money = self.model.price;
        vc.order_id = data;
        vc.order_type = @"nursery";
        [self pushViewController:vc animated:1];
        // DDLogInfo(@"json = \n%@",modelDic.mj_JSONString);
        DDLogInfo(@"%@请求成功:resp\n%@",stoneobs_net_net_url,responseObject);
        
        
    } failure:^(NSString *stateCode, STTools_Error *error,NSError *originError) {
        [SVProgressHUD dismiss];
        [SVProgressHUD showErrorWithStatus:error.desc];
        DDLogError(@"\n请求失败:\nurl:%@\nparam:%@\n失败原因:%@\n错误码:%ld",
                   stoneobs_net_net_url,stoneobs_net_param_dic,error.desc,error.code);
    }];

}
@end
